<template>
  <div>
    <el-row class="step">
      <el-col :span="24">
        <el-steps :active="step" finish-status="success">
          <el-step title="基本信息"></el-step>
          <el-step title="规格参数"></el-step>
          <el-step title="销售属性"></el-step>
          <el-step title="SKU信息"></el-step>
          <el-step title="保存完成"></el-step>
        </el-steps>
      </el-col>
      <!--基本信息开始-->
      <el-col :span="24" v-show="step==0">
        <el-card class="box-card" style="width:80%;margin:20px auto">
          <el-form ref="spuInfoForm" :model="spuInfo" label-width="120px" :rules="spuInfoRules">
            <el-form-item label="商品名称" prop="spuName">
              <el-input v-model="spuInfo.spuName"></el-input>
            </el-form-item>
            <el-form-item label="商品描述" prop="spuDescription">
              <el-input v-model="spuInfo.spuDescription"></el-input>
            </el-form-item>
            <el-form-item label="所属分类" prop="catalogId">
              <categoryCascader @handleChange="handleChange" :cascaderWidth="cascaderWidth" :catelogPath="catalogIds"/>
            </el-form-item>
            <el-form-item label="品牌" prop="brandId">
              <el-select v-model="spuInfo.brandId" filterable placeholder="请选择">
                <el-option
                  v-for="dict in brandList"
                  :key="dict.brandId"
                  :label="dict.brandName"
                  :value="dict.brandId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品重量(Kg)" prop="weight">
              <el-input-number v-model.number="spuInfo.weight" :min="0" :precision="3" :step="0.1"></el-input-number>
            </el-form-item>
            <el-form-item label="设置积分" prop="bounds">
              <label>金币</label>
              <el-input-number
                style="width:130px"
                placeholder="金币"
                v-model="spuInfo.bounds.buyBounds"
                :min="0"
                controls-position="right"
              ></el-input-number>
              <label style="margin-left:15px">成长值</label>
              <el-input-number
                style="width:130px"
                placeholder="成长值"
                v-model="spuInfo.bounds.growBounds"
                :min="0"
                controls-position="right"
              >
                <template slot="prepend">成长值</template>
              </el-input-number>
            </el-form-item>
            <el-form-item label="商品介绍" prop="decript">
              <ImageUpload :returnType="false" v-model="spuInfo.decript"/>
            </el-form-item>
            <el-form-item label="商品图集" prop="images">
              <ImageUpload :returnType="false" v-if="showImg" v-model="spuInfo.images"/>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="collectSpuInfo">下一步：设置基本参数</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <!--基本信息结束-->
      <!--规格参数开始 -->
      <el-col :span="24" v-show="step==1">
        <el-card class="box-card" style="width:80%;margin:20px auto">
          <el-tabs tab-position="left" style="width:98%">
            <el-tab-pane
              :label="group.attrGroupName"
              v-for="(group,gidx) in attrGroupWithAttr.attrGroups"
              :key="group.attrGroupId"
            >
              <!-- 遍历属性,每个tab-pane对应一个表单，每个属性是一个表单项  spuInfo.baseAttrs[0] = [{attrId:xx,val:}]-->
              <el-form ref="form" :model="spuInfo">
                <el-form-item
                  :label="attr.attrName"
                  v-for="(attr,aidx) in group.mallAttrVoList"
                  :key="attr.attrId"
                >
                  <el-input
                    v-model="attrGroupWithAttr.baseAttrs[gidx][aidx].attrId"
                    type="hidden"
                    v-show="false"
                  ></el-input>
                  <el-select
                    v-model="attrGroupWithAttr.baseAttrs[gidx][aidx].attrValues"
                    style="width: 400px;padding-right:10px "
                    :multiple="attr.valueType == 1"
                    filterable
                    allow-create
                    default-first-option
                    placeholder="请选择或输入值"
                  >
                    <el-option
                      v-for="(val,vidx) in attr.valueSelect.toString().split(',')"
                      :key="vidx"
                      :label="val"
                      :value="val"
                    ></el-option>
                  </el-select>
                  <el-checkbox
                    v-model="attrGroupWithAttr.baseAttrs[gidx][aidx].showDesc"
                    :true-label="1"
                    :false-label="0"
                  >快速展示</el-checkbox>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
          <div style="margin:auto">
            <el-button type="primary" @click="stepPrev">上一步</el-button>
            <el-button type="success" @click="generateSaleAttrs">下一步：设置销售属性</el-button>
          </div>
        </el-card>
      </el-col>
      <!--规格参数结束-->
      <!--销售属性开始-->
      <el-col :span="24" v-show="step==2">
        <el-card class="box-card" style="width:80%;margin:20px auto">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>选择销售属性</span>
              <el-form ref="saleform" :model="spuInfo" @submit.native.prevent>
                <el-form-item
                  :label="attr.attrName"
                  v-for="(attr,aidx) in attrGroupWithAttr.saleAttrs"
                  :key="attr.attrId"
                >
                  <el-input
                    v-model="attrGroupWithAttr.tempSaleAttrs[aidx].attrId"
                    type="hidden"
                    v-show="false"
                  ></el-input>
                  <el-checkbox-group v-model="attrGroupWithAttr.tempSaleAttrs[aidx].attrValues">
                   <el-checkbox
                      v-if="attrGroupWithAttr.saleAttrs[aidx].valueSelect != ''"
                      :label="val"
                      v-for="(val,index) in attrGroupWithAttr.saleAttrs[aidx].valueSelect.split(',')"
                      :key="index"
                    ></el-checkbox>
                    <div style="margin-left:20px;display:inline">
                      <el-button
                        v-show="!inputVisible[aidx].view"
                        class="button-new-tag"
                        size="mini"
                        @click="showInput(aidx)"
                      >+自定义</el-button>
                      <el-input
                        v-show="inputVisible[aidx].view"
                        v-model="inputValue[aidx].val"
                        :ref="'saveTagInput'+aidx"
                        size="mini"
                        style="width:150px"
                        @keyup.enter.native="handleInputConfirm(aidx)"
                        @blur="handleInputConfirm(aidx)"
                      ></el-input>
                    </div>
                  </el-checkbox-group>
                </el-form-item>
              </el-form>
            </div>
            <el-button type="primary" @click="step = 1">上一步</el-button>
            <el-button type="success" @click="generateSkus">下一步：设置SKU信息</el-button>
          </el-card>
        </el-card>
      </el-col>
      <!--销售属性结束-->
      <!--sku开始-->
      <el-col :span="24" v-show="step==3">
        <el-card class="box-card" style="width:80%;margin:20px auto">
          <el-table :data="spuInfo.skus" style="width: 100%">
            <el-table-column label="属性组合">
              <el-table-column
                :label="item.attrName"
                v-for="(item,index) in attrGroupWithAttr.tableAttrColumn"
                :key="item.attrId"
              >
                <template slot-scope="scope">
                  <span style="margin-left: 10px">{{ scope.row.attr[index].attrValue }}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="商品名称" prop="skuName">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuName"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="标题" prop="skuTitle">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuTitle"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="副标题" prop="skuSubtitle">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuSubtitle"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="价格" prop="price">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price"></el-input>
              </template>
            </el-table-column>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-row>
                  <el-col :span="24">
                    <label style="display:block;float:left">选择图集 或</label>
                    <ImageUpload :returnType="false" :isImgShow="false" v-model="uploadImages"/>
                  </el-col>
                  <el-col :span="24">
                    <el-divider></el-divider>
                  </el-col>
                  <el-col :span="24">
                    <el-card
                      style="width:200px;float:left;margin:15px;"
                      :body-style="{ padding: '0px' }"
                      v-for="(img,index) in spuInfo.images"
                      :key="index"
                    >
                      <img :src="img" style="width:160px;height:120px;margin:18px;" />
                      <div style="padding: 14px;" v-if="showAttr">
                        <el-row>
                          <el-col :span="12">
                            <el-checkbox
                              v-if="scope.row.images.length>0"
                              v-model="scope.row.images[index].imgUrl"
                              :true-label="img"
                              false-label
                            ></el-checkbox>
                          </el-col>
                          <el-col :span="12">
                            <el-tag v-if="scope.row.images[index].defaultImg == 1">
                              <input
                                type="radio"
                                checked
                                :name="scope.row.skuName"
                                @change="checkDefaultImg(scope.row,index,img)"
                              />设为默认
                            </el-tag>
                            <el-tag v-else>
                              <input
                                type="radio"
                                :name="scope.row.skuName"
                                @change="checkDefaultImg(scope.row,index,img)"
                              />设为默认
                            </el-tag>
                          </el-col>
                        </el-row>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
                <!-- 折扣，满减，会员价 -->
                <el-form :model="scope.row">
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="设置折扣">
                        <label>满</label>
                        <el-input-number
                          style="width:160px"
                          :min="0"
                          controls-position="right"
                          v-model="scope.row.fullCount"
                        ></el-input-number>
                        <label>件</label>

                        <label style="margin-left:15px;">打</label>
                        <el-input-number
                          style="width:160px"
                          v-model="scope.row.discount"
                          :precision="2"
                          :min="0"
                          :step="0.01"
                          controls-position="right"
                        ></el-input-number>
                        <label>折</label>
                        <el-checkbox
                          v-model="scope.row.countStatus"
                          :true-label="1"
                          :false-label="0"
                        >可叠加优惠</el-checkbox>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="设置满减">
                        <label>满</label>
                        <el-input-number
                          style="width:160px"
                          v-model="scope.row.fullPrice"
                          :min="0"
                          controls-position="right"
                        ></el-input-number>
                        <label>元</label>
                        <label style="margin-left:15px;">减</label>
                        <el-input-number
                          style="width:160px"
                          v-model="scope.row.reducePrice"
                          :min="0"
                          controls-position="right"
                        ></el-input-number>
                        <label>元</label>
                        <el-checkbox
                          v-model="scope.row.priceStatus"
                          :true-label="1"
                          :false-label="0"
                        >可叠加优惠</el-checkbox>
                      </el-form-item>
                    </el-col>

                    <el-col :span="24">
                      <el-form-item label="设置会员价" v-if="scope.row.memberPrice.length>0">
                        <br />
                        <!--   @change="handlePriceChange(scope,mpidx,$event)" -->
                        <el-form-item v-for="(mp,mpidx) in scope.row.memberPrice" :key="mp.id">
                          {{mp.name}}
                          <el-input-number
                            style="width:160px"
                            v-model="scope.row.memberPrice[mpidx].price"
                            :precision="2"
                            :min="0"
                            controls-position="right"
                          ></el-input-number>
                        </el-form-item>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="step = 2">上一步</el-button>
          <el-button type="success" @click="submitSkus">下一步：保存商品信息</el-button>
        </el-card>
      </el-col>
      <!--sku结束-->
      <el-col :span="24" v-show="step==4">
        <el-card class="box-card" style="width:80%;margin:20px auto">
          <h1>保存成功</h1>
          <el-button type="primary" @click="addAgian">继续添加</el-button>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import categoryCascader from '@/views/components/category-cascader';
  import ImageUpload from '@/components/ImageUpload';
  import {queryListByCatelogId } from "@/api/mall/pms/categoryBrand";
  import {getAttrGroupWithAttrByCatelogId} from "@/api/mall/pms/attrGroup";
  import {getListByCatelogId} from "@/api/mall/pms/attr";
  import {memberLevelList} from "@/api/mall/ums/memberLevel";
  import {saveProduct} from "@/api/mall/pms/product";

  export default {
    components: {
      categoryCascader,
      ImageUpload
    },
    data() {
      return {
        showImg:true,
        showAttr:true,
        //分类id
        catalogIds: [],
        //级联选择器宽度
        cascaderWidth:'500px',
        //品牌集合
        brandList:[],
        //分类id
        catalogId:'',
        //步骤条
        step: 0,
        //sup信息
        spuInfo: {
          //要提交的数据
          spuName: "",
          spuDescription: "",
          catalogId: 0,
          brandId: "",
          weight: "",
          publishStatus: 2,
          decript: [], //商品详情
          images: [], //商品图集，最后sku也可以新增
          bounds: {
            //积分
            buyBounds: 0,
            growBounds: 0
          },
          baseAttrs: [], //基本属性
          skus: [] //所有sku信息
        },
        attrGroupWithAttr: {
          //后台返回的所有数据
          attrGroups: [],
          baseAttrs: [],
          saleAttrs: [],
          tempSaleAttrs: [],
          tableAttrColumn: [],
          memberLevels: [],
          steped: [false, false, false, false, false]
        },
        //新增销售属性是否显示
        inputVisible: [],
        //新增销售属性的值
        inputValue: [],
        //上传的图集
        uploadImages: '',
        spuInfoRules: {
          spuName: [
            {required: true, message: "请输入商品名字", trigger: "blur"}
          ],
          spuDescription: [
            {required: true, message: "请编写一个简单描述", trigger: "blur"}
          ],
          catalogId: [
            {required: true, message: "请选择一个分类", trigger: "blur"}
          ],
          brandId: [
            {required: true, message: "请选择一个品牌", trigger: "blur"}
          ],
          decript: [
            {required: true, message: "请上传商品详情图集", trigger: "blur"}
          ],
          images: [
            {required: true, message: "请上传商品图片集", trigger: "blur"}
          ],
          weight: [
            {
              type: "number",
              required: true,
              message: "请填写正确的重量值",
              trigger: "blur"
            }
          ]
        },
      }
    },
    //监控data中的数据变化
    watch: {
      uploadImages(val) {
          if(val.length>1){
            val=val[val.length-1];
          }
          //扩展每个skus里面的imgs选项
          let imgArr = Array.from(new Set(this.spuInfo.images.concat(val)));
          //{imgUrl:"",defaultImg:0} 由于concat每次迭代上次，有很多重复。所以我们必须得到上次+这次的总长
          this.spuInfo.skus.forEach((item, index) => {
            let len = imgArr.length - this.spuInfo.skus[index].images.length; //还差这么多
            if (len > 0) {
              let imgs = new Array(len);
              imgs = imgs.fill({ imgUrl: "", defaultImg: 0 });
              this.spuInfo.skus[index].images = item.images.concat(imgs);
            }
          });
          this.spuInfo.images = imgArr; //去重
      }
    },
    mounted(){
    },
    methods: {
      //下一步 规格参数
      collectSpuInfo(){
        this.$refs.spuInfoForm.validate(valid => {
          if (valid) {
            this.step = 1;
            //查询分组与规格参数
            this.getAttrGroupWithAttrByCatelogId()
            //按照分类id查询销售属性
            this.getAttrListByCatelogId()
            //全部会员
            this.memberLevelList()
          } else {
            return false;
          }
        });
      },
      //上一步
      stepPrev(){
        this.showImg=true;
        this.showAttr=false;
        this.step = 0;
      },
      //下一步 销售属性
      generateSaleAttrs(){
        if (!this.attrGroupWithAttr.steped[1]) {
          //把页面绑定的所有attr处理到spu里面,这一步都要做
          this.spuInfo.baseAttrs = [];
          this.attrGroupWithAttr.baseAttrs.forEach(item => {
            item.forEach(attr => {
              let { attrId, attrValues, showDesc } = attr;
              //跳过没有录入值的属性
              if (attrValues != "") {
                if (attrValues instanceof Array) {
                  //多个值用;隔开
                  attrValues = attrValues.join(",");
                }
                this.spuInfo.baseAttrs.push({ attrId, attrValues, showDesc });
              }
            });
          });
          this.step = 2;
        }
      },
      //下一步 sku
      generateSkus() {
        this.showImg=false;
        this.step = 3;
        //根据笛卡尔积运算进行生成sku
        let selectValues = [];
          this.attrGroupWithAttr.tableAttrColumn = [];
          this.attrGroupWithAttr.tempSaleAttrs.forEach(item => {
            if (item.attrValues.length > 0) {
              selectValues.push(item.attrValues);
              this.attrGroupWithAttr.tableAttrColumn.push(item);
            }
          });
          let descartes = this.descartes(selectValues);
          //有多少descartes就有多少sku
          let skus = [];
          descartes.forEach((descar, descaridx) => {
            let attrArray = []; //sku属性组
            descar.forEach((de, index) => {
              //构造saleAttr信息
              let saleAttrItem = {
                attrId: this.attrGroupWithAttr.tableAttrColumn[index].attrId,
                attrName: this.attrGroupWithAttr.tableAttrColumn[index].attrName,
                attrValue: de
              };
              attrArray.push(saleAttrItem);
            });
            //先初始化几个images，后面的上传还要加

            let imgs = [];
            this.spuInfo.images.forEach((img, idx) => {
              imgs.push({ imgUrl: "", defaultImg: 0 });
            });
            //会员价，也必须在循环里面生成，否则会导致数据绑定问题
            let memberPrices = [];
            if (this.attrGroupWithAttr.memberLevels.length > 0) {
              for (let i = 0; i < this.attrGroupWithAttr.memberLevels.length; i++) {
                if (this.attrGroupWithAttr.memberLevels[i].priviledgeMemberPrice == 1) {
                  memberPrices.push({
                    id: this.attrGroupWithAttr.memberLevels[i].id,
                    name: this.attrGroupWithAttr.memberLevels[i].name,
                    price: 0
                  });
                }
              }
            }
            //;descaridx，判断如果之前有就用之前的值;
            let res = this.hasAndReturnSku(this.spuInfo.skus, descar);
            if (res === null) {
              skus.push({
                attr: attrArray,
                skuName: this.spuInfo.spuName + " " + descar.join(" "),
                price: 0,
                skuTitle: this.spuInfo.spuName + " " + descar.join(" "),
                skuSubtitle: "",
                images: imgs,
                descar: descar,
                fullCount: 0,
                discount: 0,
                countStatus: 0,
                fullPrice: 0.0,
                reducePrice: 0.0,
                priceStatus: 0,
                memberPrice: new Array().concat(memberPrices)
              });
            } else {
              skus.push(res);
            }
          });
          this.$nextTick(()=>{
            this.spuInfo.skus = skus;
          })

      },
      //提交保存
      submitSkus() {
        this.$confirm("将要提交商品数据，需要一小段时间，是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.spuInfo.catalogId=this.catalogId;
            saveProduct(this.spuInfo).then(response => {
              console.log(response)
              if(response.code==200){
                this.msgSuccess("保存成功");
              }
            }).catch(() => {
            });
          })
          .catch(e => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      },
      addAgian() {
        this.step = 0;
        // this.resetSpuData();
      },
      //判断如果包含之前的sku的descar组合，就返回这个sku的详细信息；
      hasAndReturnSku(skus, descar) {
        let res = null;
        if (skus.length > 0) {
          for (let i = 0; i < skus.length; i++) {
            if (skus[i].descar.join(" ") == descar.join(" ")) {
              res = skus[i];
            }
          }
        }
        return res;
      },
      checkDefaultImg(row, index, img) {
        //这个图片被选中了，
        row.images[index].imgUrl = img; //默认选中
        row.images[index].defaultImg = 1; //修改标志位;
        //修改其他人的标志位
        row.images.forEach((item, idx) => {
          if (idx != index) {
            row.images[idx].defaultImg = 0;
          }
        });
      },
      //新增销售属性
      showInput(idx) {
        this.inputVisible[idx].view = true;
      },
      handleInputConfirm(idx) {
        let inputValue = this.inputValue[idx].val;
        let flag=true;
        this.attrGroupWithAttr.saleAttrs[idx].valueSelect.split(",").forEach(e=>{
          if(e===inputValue){
            this.msgWarning("该属性已存在！");
            flag=false;
            return false;
          }
        })
        if (flag==true&&inputValue) {
          if (this.attrGroupWithAttr.saleAttrs[idx].valueSelect == "") {
            this.attrGroupWithAttr.saleAttrs[idx].valueSelect = inputValue;
          } else {
            this.attrGroupWithAttr.saleAttrs[idx].valueSelect += "," + inputValue;
          }
        }
        this.inputVisible[idx].view = false;
        this.inputValue[idx].val = "";
      },
      //笛卡尔积运算
      descartes(list) {
        //parent上一级索引;count指针计数
        var point = {};
        var result = [];
        var pIndex = null;
        var tempCount = 0;
        var temp = [];
        //根据参数列生成指针对象
        for (var index in list) {
          if (typeof list[index] == "object") {
            point[index] = { parent: pIndex, count: 0 };
            pIndex = index;
          }
        }
        //单维度数据结构直接返回
        if (pIndex == null) {
          return list;
        }
        //动态生成笛卡尔积
        while (true) {
          for (var index in list) {
            tempCount = point[index]["count"];
            temp.push(list[index][tempCount]);
          }
          //压入结果数组
          result.push(temp);
          temp = [];
          //检查指针最大值问题
          while (true) {
            if (point[index]["count"] + 1 >= list[index].length) {
              point[index]["count"] = 0;
              pIndex = point[index]["parent"];
              if (pIndex == null) {
                return result;
              }
              //赋值parent进行再次检查
              index = pIndex;
            } else {
              point[index]["count"]++;
              break;
            }
          }
        }
      },
      //选择关联的分类
      handleChange(data) {
        this.catalogIds = data;
        this.catalogId=this.catalogIds[this.catalogIds.length-1];
        //查询品牌
        this.queryBrandListByCatelogId()

      },
      /** 按分类id查询品牌 */
      queryBrandListByCatelogId() {
        queryListByCatelogId(this.catalogId).then(response => {
          this.brandList = response.data;
        }).catch(() => {
        });
      },
      /** 查询会员等级 */
      memberLevelList() {
        memberLevelList(null).then(response => {
          this.attrGroupWithAttr.memberLevels = response.data;
        }).catch(() => {
        });
      },
      //按照分类id查询销售属性
      getAttrListByCatelogId(){
        getListByCatelogId(this.catalogId).then(response => {
          if(response.code==200&&response.data.length>0){
            this.attrGroupWithAttr.saleAttrs = response.data;
            response.data.forEach(attr => {
              this.attrGroupWithAttr.tempSaleAttrs.push({
                attrId: attr.attrId,
                attrValues: [],
                showDesc: attr.showDesc
              });
              this.inputVisible.push({ view: false });
              this.inputValue.push({ val: "" });
            })
          }
        })
      },
      /** 按分类id查询分组与属性 */
      getAttrGroupWithAttrByCatelogId() {
        getAttrGroupWithAttrByCatelogId(this.catalogId).then(response => {
            //分组
            this.attrGroupWithAttr.attrGroups = response.data;
            //规格参数属性
            //先对表单的baseAttrs进行初始化
            response.data.forEach(item => {
              let attrArray = [];
              if(item.mallAttrVoList!=null&&item.mallAttrVoList.length>0){
                item.mallAttrVoList.forEach(attr => {
                    attrArray.push({
                      attrId: attr.attrId,
                      attrValues: "",
                      showDesc: attr.showDesc
                    });
                });
             }
              this.attrGroupWithAttr.baseAttrs.push(attrArray);
            });
        }).catch(() => {
        });
      },

    }
  }
</script>

<style scoped>
  .step {
    padding: 30px 30px;
  }
</style>
